﻿using RockBus.Monitoring.DataContracts.Configuration;
using RockBus.Monitoring.DataContracts;
using RockBus.Utilities;
using System;
using System.Diagnostics;

namespace RockBus.Monitoring
{
    /// <summary>
    /// Collects the performance counter value.
    /// </summary>
    internal class PerformanceCounterCollector : PerformanceCounterCollectorBase
    {
        public PerformanceCounterCollector(PerformanceCounterConfiguration pcc, int bufferSize)
            : base(pcc, bufferSize)
        {
        }

        /// <summary>
        /// Collects the performance counter value.
        /// </summary>
        /// <param name="timestamp">The timestamp to apply to the performance counter value collection. This parameter is necessary to synchronize the performance counter collection accross multiple collectors.</param>
        public override void Collect()
        {
            var pcc = new System.Diagnostics.PerformanceCounterCategory(this.PerformanceCounterConfigurationBase.CategoryName);
            var idcc = pcc.ReadCategory();

            if ((null == idcc) || (idcc.Count == 0))
            {
                return;
            }

            var currentInstanceDataCollection = idcc[this.PerformanceCounterConfigurationBase.CounterName];
            foreach (InstanceData currentInstanceData in currentInstanceDataCollection.Values)
            {
                this.AddCounterSample(this.PerformanceCounterConfigurationBase.CounterName, currentInstanceData.InstanceName, currentInstanceData.Sample);
            }
        }
    }
}